package com.qf.service.impl;

import com.qf.dao.OrderDao;
import com.qf.dao.impl.OrderDaoImpl;
import com.qf.pojo.Order;
import com.qf.pojo.OrderItem;
import com.qf.service.OrderService;
import com.qf.utils.JdbcUtils;
import com.sun.org.apache.xpath.internal.operations.Or;

import java.sql.Connection;
import java.sql.SQLException;

/**
 *
 */
public class OrderServiceImpl implements OrderService {
    @Override
    public void addOrder(Order order) {

        Connection connection = null ;
        try {
            //使用事务
            //开启事务
           // JdbcUtils.setAutoCommit();
           connection = JdbcUtils.getConnection();
            connection.setAutoCommit(false);

            //需要调用OrderDao ---->给订单表中加入数据
            OrderDao orderDao  = new OrderDaoImpl() ;
            orderDao.insertOrder(order);


            //来个异常
//            int i = 10 / 0 ;

            //获取每一个订单项
            for(OrderItem orderItem:order.getItems()){
                //需要调用OrderDao ---->给订单项表中加入数据
                orderDao.insertOrderItem(orderItem);
            }

            //提交事务
            //JdbcUtils.commitAndClose();
            connection.commit();

        } catch (SQLException e) {
            try {
                //如果执行 catch语句,说明存在问题,应该回滚事务
                //JdbcUtils.rollbackAndClose();

                connection.rollback();
                e.printStackTrace();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }


    }

    /**
     * 更新订单的用户数据
     * @param order
     */
    @Override
    public void updateOrder(Order order) {
        try {
            //调用业务接口
            OrderDao orderDao = new OrderDaoImpl() ;
            orderDao.update(order);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    /**
     * 支付宝支付的时候:通过订单编号获取订单实体
     * @param orderNO
     * @return
     */
    @Override
    public Order getOrderById(String orderNO) {

        try {
            //调用数据访问接口获取订单实体
            OrderDao orderDao = new OrderDaoImpl() ;
            Order order = orderDao.selectOrderById(orderNO) ;
            if(order!=null){
                return  order;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    //更新订单支付状态
    @Override
    public void updateOrderState(Order order) {

        try {
            //调用OrderDao
            OrderDao orderDao = new OrderDaoImpl() ;
            orderDao.updateState(order) ;
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
